package com.tms.control;

import com.tms.domain.LifeCycle;
import com.tms.domain.Tool;
import com.tms.service.LifeCycleService;
import com.tms.service.ToolService;
import com.tms.utils.Data;
import com.tms.utils.JsonResult;
import com.tms.utils.token.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.tms.core.constants.LifeCycleConstants.*;
import static com.tms.core.constants.LifeCycleConstants.SUCCESS;

/**
 * 生命周期记录控制类
 */
@RestController
@RequestMapping("/api/lifeCycles")
public class LifeCycleController extends BaseController {

    @Autowired
    private LifeCycleService lifeCycleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ToolService toolService;

    @GetMapping
    public JsonResult viewLifeCycle(@RequestParam(value = "toolId") int toolId, HttpServletRequest request) {
        int workcellId = tokenService.getWorkcellId(request);
        if (workcellId == 0) {
            return new JsonResult(ERROR_TOKEN.getStatus(), ERROR_TOKEN.getDesc());
        }
        Tool tool = toolService.findToolById(toolId);
        if (tool == null) {
            return new JsonResult(ERROR_NULL_TOOL.getStatus(), ERROR_NULL_TOOL.getDesc());
        } else if (tool.getTDef().getWorkcell().getId() != workcellId) {
            return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
        }
        List<LifeCycle> lifeCycles = lifeCycleService.findLifeCycleByCodeAndSeqId(toolId);
        if (lifeCycles == null || lifeCycles.isEmpty()) {
            return new JsonResult(ERROR_NULL_LIFECYCLE.getStatus(), ERROR_NULL_LIFECYCLE.getDesc());
        }
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data("lifeCycles", lifeCycles));
    }

}